﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System.Reflection;
using QiAdmin.Core;
using QiAdmin.Core.Attributes;
using QiAdmin.Core.Models;
using QiAdmin.Core.Services.Cache;
using QiAdmin.Core.Services.Quartz;
using QiAdmin.Core.Utils;
using QiAdmin.Model.Dtos.Input;
using QiAdmin.Model.System.Models;
using QiAdmin.Repository.Repository;
using QiAdmin.Service.IService;
using QiAdmin.Service.Service;

namespace QiAdmin.WebApi.Controllers.System
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class SysPublicController : ControllerBase
    {
        readonly ICacheService _cacheService;
        readonly ITSysFilesService _tSysFilesService;
        public SysPublicController(ICacheService cacheService, ITSysFilesService tSysFilesService)
        {
            _cacheService = cacheService;
            _tSysFilesService = tSysFilesService;
        }

        [HttpGet]
        public ApiJsonResult Index()
        {
            return ApiJsonResult.Success;
        }

        [HttpGet]
        public async Task<ApiJsonResult> GetSentence()
        {
            string result = "生活变的再糟糕，也不妨碍我变得更好！";

            string cacheKey = "Cache_Sentence";
            var cache = _cacheService.Get<string>(cacheKey);
            if (cache == null)
            {
                HttpClient client = new HttpClient();
                client.Timeout = new TimeSpan(0, 0, 20);
                try
                {
                    var res = await client.GetAsync("http://sentence.iciba.com/index.php?c=dailysentence&m=getdetail&title=" + DateTime.Now.ToString("yyyy-MM-dd"));
                    string content = await res.Content.ReadAsStringAsync();
                    JObject jobj = JObject.Parse(content);
                    if (jobj["errno"].ToString() == "0")
                    {
                        result = jobj["note"].ToString();
                        var expires=DateTime.Now.AddDays(1).Date-DateTime.Now;
                        _cacheService.Add(cacheKey, result, expires);
                    }
                }
                catch { }
            }
            else
            {
                result = cache;
            }

            return new ApiJsonResult(ResultType.Success, result);
        }

        [HttpGet]
        public IActionResult DownLoad(string fileName,string? pwd)
        {
            var path = _tSysFilesService.ShareDownload(fileName,pwd);
            if (path.IsSuccess)
            {
                FileStream fileStream = new FileStream(path.Result, FileMode.Open);
                FileStreamResult streamResult = new FileStreamResult(fileStream, "application/octet-stream")
                {
                    FileDownloadName = fileName
                };
                return streamResult;
            }else
            {
                return Content(path.Msg);
            }
        }
    }
}
